if (localStorage.quizzJson) {
  quizz = JSON.parse(localStorage.quizzJson);
} else {
  localStorage.quizzJson = JSON.stringify(quizz);;
}

var prefixStore = 'PokerQuizz';
    storeKeyScore = prefixStore + 'Score',
    noPoints = '-';
if (!localStorage[storeKeyScore]) {
  localStorage[storeKeyScore] = [];
}
buildQuizzRouteurPage();

//======================================================
//= Initilization
//======================================================

// Init footer.
$("div[data-role='footer']").html(
    $('#footerTemplate').html());


/**
 * Routeur of the application
 */
$(document).bind('pagebeforechange', function(e, data) {
	if (typeof data.toPage === "string") {
	  u = $.mobile.path.parseUrl(data.toPage);
	  if (u.hash.search('quizz') !== -1) {
	    goToQuizzPage(u.hash);
	  } else if (u.hash == '#endQuizz') {
	    buildEndQuizzPage();
	  } else if (u.hash == '#routeurQuizz') {
	    buildQuizzRouteurPage();
	  } else if (u.hash == '#optionsPage') {
	    buildOptionsPage();	
	  }
	}
	buildHomePage();
  }
)


/**
 * Builds Home Page.
 */
function buildHomePage() {
  setTimeout("$('#homePage .ui-footer #home').addClass('ui-btn-active');", 100);
  $('#homePage .content').height(window.innerHeight);
}


//======================================================
//= Quizz Logic
//======================================================
var currentQuizzScore = 0,
    currentNumberQuestionAnswered = 0;
    currentIdQuizz = null,
    currentIdQuestion = null;

    
function goToQuizzPage(quizz) {
  quizz = quizz.replace('#quizz', '');
  quizzSplitted = quizz.split('-')
  currentIdQuizz = quizzSplitted[0];
  currentIdQuestion = quizzSplitted[1];
  if (currentIdQuestion == 0) {
    initQuizz();
  }
  buildQuestionPage();
}


function initQuizz() {
  currentQuizzScore = 0;
  currentNumberQuestionAnswered = 0;
}

/**
 * Builds the question page
 */
function buildQuestionPage() {
  var questionPage = $('#pageModel').clone();
  var question = quizz[currentIdQuizz]['questions'][currentIdQuestion];
  
  questionPage.attr('id', 'quizz' + currentIdQuizz + '-' + currentIdQuestion);
  questionPage.find('#questionTitle').html(question['title']);
  
  var fieldset = $('<fieldset></fieldset>');
  fieldset.attr('data-role', 'controlgroup');
  for (var i = 0; i < question['answers'].length; i++) {
    var inputEl = $('<input/>');
    inputEl.attr('type', 'radio');
    inputEl.attr('data-theme', 'l');
    inputEl.attr('name', 'answer' + currentIdQuizz + '-' + currentIdQuestion);
    inputEl.attr('id', 'answer' + i);
    inputEl.attr('value', question['answers'][i]);
    var labelEl = $('<label></label>');
    labelEl.attr('for', 'answer' + i);
    labelEl.html(question['answers'][i]);
    fieldset.append(inputEl);
    fieldset.append(labelEl);
  }
  var answers = $('<div></div>');
  answers.attr('data-role', 'fieldcontain');
  answers.append(fieldset);
  
  questionPage.find('#quizzName').html(quizz[currentIdQuizz]['title']);
  questionPage.find('#questionsBlock').html('');
  questionPage.find('#questionsBlock').append(answers);
  questionPage.find('#questionsBlock').trigger('create');
  questionPage.find('#validateButtonWrapper').show();
  questionPage.find('#nextQuestionLink').
      attr('href', getFinalPageLink()).hide();
  updateScore(questionPage);
  addPage(questionPage);
}

function removeBuiltPage() {
  $('.builtPage').each(function() {
  	if (!$(this).hasClass('ui-page-active')) {
  	  $(this).remove();
  	}
  })
}


function getFinalPageLink() {
	console.log(parseInt(currentIdQuestion))
	console.log(	this.getCurrentQuestions().length - 1)	
    console.log(parseInt(currentIdQuestion) != this.getCurrentQuestions.length - 1);
  if (parseInt(currentIdQuestion) != (this.getCurrentQuestions().length - 1)) {
    console.log(	'NE')	
    return '#quizz' + currentIdQuizz +
        '-' + (parseInt(currentIdQuestion) + 1);
  } else {
    return '#endQuizz';
  }
}

/**
 * Validates the question.
 */
function validateQuestion() {
  var question = currentQuestion();
  var page = getCurrentPage();
  var positiveAnswer = false;
  if (question['type'] == 'radio') {
    positiveAnswer = validateRadioQuestion();
  }
  console.log('question' + positiveAnswer);
  if (positiveAnswer) {
    currentQuizzScore++;	
    page.find('#positiveReply').show();
  } else {
    page.find('#negativeReply').show();
  }
  page.find('.explanation').html(question['comment']);
  currentNumberQuestionAnswered++;
  updateScore(page);
  page.find('#validateButtonWrapper').hide();
  page.find('#nextQuestionLink').show();
}

function currentIdPage() {
  return 'quizz' + currentIdQuizz + '-' + currentIdQuestion;
}

function getCurrentPage() {
  return $('#' + currentIdPage());	
}

function currentQuestion() {
  return quizz[currentIdQuizz]['questions'][currentIdQuestion];
}

function validateRadioQuestion() {
  var question = quizz[currentIdQuizz]['questions'][currentIdQuestion];
  var questionPage = getCurrentPage();
  var answerLabel = questionPage.find('.ui-radio .ui-radio-on').attr('for');
  if (answerLabel != undefined) {
    var answerNumber = answerLabel.replace('answer', '');
  }
  return (answerNumber == question['answer']);	
}


function nextQuestion() {
  buildQuestionPage();
}

function updateScore(page) {
  page.find('.currentScore').html(currentQuizzScore);
  page.find('.questionsAnswered').html(currentNumberQuestionAnswered);
  page.find('.totalQuestions').html(getCurrentQuestions().length);
}

function getCurrentQuestions() {
  return quizz[currentIdQuizz]['questions'];
}

/**
 * Builds the page to end a quizz.
 */
function buildEndQuizzPage() {
  var finalPage = $('#pageModel').clone();
  finalPage.attr('id', 'endQuizz');
  finalPage.find('#quizzName').html(quizz[currentIdQuizz]['title']);
  finalPage.find('#questionTitle').html('Fin du Quizz');
  updateScore(finalPage);
  finalPage.find('#validateButtonWrapper').hide();
  finalPage.find('#nextQuestionLink').hide();
  saveScore();
  addPage(finalPage);
}


function saveScore() {console.log(currentIdQuestion);
  localStorage[storeKeyScore + currentIdQuizz] = currentQuizzScore;
}

function addPage(pageToAdd) {
  removeBuiltPage();
  pageToAdd.addClass('builtPage');
  $('body').append(pageToAdd);
}

//======================================================
//= Home Page Logic
//======================================================
function buildQuizzRouteurPage() {
  removeBuiltPage();
  var categoriesWrapper = $('#categoriesWrapper');
  var categorieList = $('<ul data-role="listview"></ul>');
  categorieList.attr('data-theme', 'p');
  categorieList.attr('data-divider-theme', 'c');
  
  for (var i = 0; i < categories.length; i++) {
    var categorie = $('<li>/li>');
    categorie.attr('id', 'categorie' + i);
    categorie.attr('data-theme', 'p');
    categorie.attr('data-icon', 'false'); 
    categorie.attr('data-role', 'list-divider');
    categorie.html('<a>Catégorie : ' + categories[i] + '</a>');
    categorieList.append(categorie);
  }

  for (var i = 0; i < quizz.length; i++) {
    var categorieTitle = categorieList.find('#categorie' + quizz[i]['category']);
    categorieTitle.after(getLiQuizzRouteurPageFromQuizzId(i));
  }
  categoriesWrapper.html(categorieList);
  if ($('#routeurQuizz').hasClass('ui-page')) {
    $('#routeurQuizz').trigger('create');
  }
}


function getLiQuizzRouteurPageFromQuizzId(i) {
	var newQuizzLi = $('<li></li>');
    var newQuizzlink = $('<a></a>');
    newQuizzlink.attr('href', '#quizz' + i + '-0');
    var currentScore = localStorage[storeKeyScore + i] ? 
        localStorage[storeKeyScore + i] : noPoints;
    newQuizzlink.html(quizz[i]['title'] + ' '    
        + ' (' + currentScore + ' / ' + quizz[i]['questions'].length + ')');
    newQuizzLi.attr('data-theme', 'o')
    newQuizzLi.append(newQuizzlink);
    return newQuizzLi;
}

//======================================================
//= Options Logic
//======================================================

function buildOptionsPage() {
  setTimeout("$('#optionsPage .ui-footer #options').addClass('ui-btn-active');", 100);
}

function resetScores() {
  for (var i = 0; i < quizz.length; i++) {
    localStorage[storeKeyScore + i] = noPoints;
  }
}

function updateQuestions() {
  $.get('http://quizzpoker.appspot.com/updatequestions',
      function(data) {
      	var jsonResponse = JSON.parse(data);
      	if (jsonResponse['status'] == 'error') {
          alert(jsonResponse['message']);
      	} else {
      	  localStorage.quizzJson = JSON.parse(data);	
      	}
      });
}


//======================================================
//= Utilities
//======================================================

function getTotalScore() {
  var score = 0;
  for (var i = 0; i < quizz.length; i++) {
    score += localStorage[storeKeyScore + i] ?
      parseInt(localStorage[storeKeyScore + i]) : 0;
  }
  return score;
}


function goToLeadeboard() {
  window.location = 'http://quizzpoker.appspot.com/leaderboard?scoreQuizz=' + getTotalScore();
}



